package com.situ.allaia.api;

import com.situ.allaia.api.common.Global;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class UploadApi {

    //上传图片
    @PostMapping("/images")
    public Map<String, Object> uploadImage(MultipartFile file, String type) throws IOException {
        //解决图片上传的问题
        if (file == null) {
            return Map.of("success", false);
        }

        //文件原始名称
        String oldName = file.getOriginalFilename();
        if (!StringUtils.hasText(oldName)) {
            return Map.of("success", false);
        }

        int extIdx = oldName.lastIndexOf(".");
        String ext = oldName.substring(extIdx);//文件扩展名

        //新名字
        String newName = UUID.randomUUID().toString() + ext;

        File target = new File(Global.UPLOAD_DIRECTORY + "/images/" + type + "/");
        if (!target.exists()) {
            target.mkdirs();//递归创建目录
        }
        //创建目标文件
        target = new File(target.getCanonicalPath() + "/" + newName);
        //复制文件
        file.transferTo(target);

        String url = "/upload/images/" + type + "/" + newName;
        return Map.of("success", true,
                "url", url, "errno", 0, "data", Map.of("url", Global.UPLOAD_SERVER_ADDR + url));

    }
}
